package com.tsoj.tsojquestionservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.tsoj.common.ErrorCode;
import com.tsoj.constant.CommonConstant;
import com.tsoj.exception.BusinessException;
import com.tsoj.model.dto.questionSubmit.QuestionSubmitAddDto;
import com.tsoj.model.dto.questionSubmit.QuestionSubmitQueryDto;
import com.tsoj.model.enums.QuestionSubmitLanguageEnum;
import com.tsoj.model.enums.QuestionSubmitStatusEnum;
import com.tsoj.model.po.Question;
import com.tsoj.model.po.QuestionSubmit;
import com.tsoj.model.po.User;
import com.tsoj.model.vo.QuestionSubmitVO;
import com.tsoj.tsojquestionservice.mapper.QuestionsubmitMapper;
import com.tsoj.tsojquestionservice.rabbitMQ.MyMessageProducer;
import com.tsoj.tsojquestionservice.service.QuestionService;
import com.tsoj.tsojquestionservice.service.QuestionsubmitService;
import com.tsoj.tsojserviceclient.service.JudgeFeignClient;
import com.tsoj.tsojserviceclient.service.UserFeignClient;
import com.tsoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 孙金硕
* @description 针对表【questionsubmit(题目提交)】的数据库操作Service实现
* @createDate 2025-04-15 10:00:08
*/
@Service
public class QuestionsubmitServiceImpl extends ServiceImpl<QuestionsubmitMapper, QuestionSubmit>
    implements QuestionsubmitService {
    @Resource
    private MyMessageProducer myMessageProducer;
    @Autowired
    private QuestionService questionService;
    @Resource
    @Lazy
    private JudgeFeignClient judgeFeignClient;
    @Override
    public long doQuestionSubmit(QuestionSubmitAddDto questionSubmitAddRequest, long userId) {
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不支持的编程语言");
        }
        //去查询看是否存在该题目
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        //写库
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserid(userId);
        questionSubmit.setQuestionid(questionId);
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeinfo("{}");
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        //todo 代码沙箱进行处理 ！！！！待处理
        //异步执行调用
//        CompletableFuture.runAsync(() ->{
//                judgeService.doJudge(questionSubmit.getId());
//        });
        //加入消息队列进行调用
        myMessageProducer.sendMessage("code_exchange","my_routingKey",String.valueOf(questionSubmit.getId()));
//        judgeFeignClient.doJudge(questionSubmit.getId());
        return questionSubmit.getId();
    }
    //todo 消息队列改造
//    @Autowired
//    private RabbitTemplate rabbitTemplate;
    public long doQuestionSubmit2(QuestionSubmitAddDto questionSubmitAddRequest, long userId) {
        String language = questionSubmitAddRequest.getLanguage();
        QuestionSubmitLanguageEnum enumByValue = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(enumByValue == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不支持的编程语言");
        }
        //去查询看是否存在该题目
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if(question == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "题目不存在");
        }
        //写库
        QuestionSubmit questionSubmit = new QuestionSubmit();
        questionSubmit.setUserid(userId);
        questionSubmit.setQuestionid(questionId);
        questionSubmit.setLanguage(language);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeinfo("{}");
        boolean save = this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        //todo 代码沙箱进行处理 ！！！！待处理
        //异步执行调用
//        CompletableFuture.runAsync(() ->{
//                judgeService.doJudge(questionSubmit.getId());
//        });
        //加入消息队列进行调用
//        rabbitTemplate.convertAndSend(RabbitMQConfig.JUDGE_QUEUE,questionSubmit.getId());
//        judgeService.doJudge(questionSubmit.getId());
        return questionSubmit.getId();
    }
    /**
     * 准备分页条件
     * @param questionSubmitQueryDto
     * @return
     */
    @Override
    public Wrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryDto questionSubmitQueryDto) {
        String language = questionSubmitQueryDto.getLanguage();
        Long questionId = questionSubmitQueryDto.getQuestionId();
        Integer status = questionSubmitQueryDto.getStatus();
        Long userId = questionSubmitQueryDto.getUserId();
        String sortField = questionSubmitQueryDto.getSortField();
        String sortOrder = questionSubmitQueryDto.getSortOrder();
        QueryWrapper<QuestionSubmit> questionSubmitQueryWrapper = new QueryWrapper<>();
        questionSubmitQueryWrapper.eq(StringUtils.isNotBlank(language), "language",language);
        questionSubmitQueryWrapper.eq(ObjectUtils.isNotEmpty(questionId),"questionId",questionId);
        questionSubmitQueryWrapper.eq(ObjectUtils.isNotEmpty(status),"status",status);
        questionSubmitQueryWrapper.eq(ObjectUtils.isNotEmpty(userId),"userId",userId);
        questionSubmitQueryWrapper.eq("isDelete",false);
        questionSubmitQueryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return questionSubmitQueryWrapper;
    }
    @Resource
    private UserFeignClient userFeignClient;
    //得到脱敏处理结果

    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOList(Page<QuestionSubmit> questionSubmitPage, Long userId) {
        List<QuestionSubmit> records = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(),
                questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        List<QuestionSubmitVO> questionSubmitVOS = records.stream().map(questionSubmit -> {
            return QuestionSubmitVO.objToVo(questionSubmit);
        }).collect(Collectors.toList());
        for (QuestionSubmitVO questionSubmitVO : questionSubmitVOS) {
            Long voUserIdd = questionSubmitVO.getUserid();
            //todo  获取用户信息有问题
            User user = userFeignClient.getById(userId);
            boolean admin = userFeignClient.isAdmin(user);
            if(!userId.equals(voUserIdd) && !admin){
                questionSubmitVO.setCode("");
            }
        }
        questionSubmitVOPage.setRecords(questionSubmitVOS);
        return questionSubmitVOPage;
    }
}




